import { defineConfig } from 'vite';
import type { PluginOption } from 'vite'
import uni from '@dcloudio/vite-plugin-uni';
import { join,resolve } from "path";
import * as fs from 'fs'

const sleep = (value = 30) =>
	new Promise((resolve) => {
		setTimeout(() => {
			resolve(null);
		}, value);
	});
function renameFile() : PluginOption {
	return {
		name: "renameFile",
		enforce: 'post',
		apply: 'build',
		async writeBundle() {
			if (process.env.UNI_SCRIPT === 'wx-platform' || process.env.UNI_SCRIPT === 'private-platform') {
				await sleep(3000)
				let build_dir = join(__dirname, 'dist/build');
				let web_dir = join(build_dir, 'web');
				let web_dir1 = join(build_dir, process.env.UNI_SCRIPT === 'wx-platform' ? '公众号' : '私域');
				
				try {
					fs.rmSync(web_dir1, { recursive: true });
				} catch (error) { }
				fs.renameSync(web_dir, web_dir1)
				console.log(`自定义发行编译成功，路径为：${web_dir1}`)

			}
		},
	};
}



export default defineConfig({
	build: {
		sourcemap: false, //源码调试
		target: ["chrome89", "edge89", "firefox89", "safari15"]
	},
	server: {
		proxy: {
			'/imHttpApi': {
				target: 'http://192.168.1.186:5050',
				changeOrigin: true,
				rewrite: (path : string) => path.replace(/^\/imHttpApi/, ''),
				cookieDomainRewrite: '' //重写cookie 的domain,在localhost上工作时，cookie域必须设置为“”或NULL或FALSE
			}
		}
	},
	plugins: [uni(), renameFile()],
	resolve: {
		alias: {
			api: resolve('common/request/api'),
			hooks: resolve('common/hooks')
		}
	}
});